<template>
  <el-drawer v-model="drawerProps.drawerVisible" :destroy-on-close="true" size="80%" :title="drawerProps.title">
    <div style="position: absolute; inset: 52px 5px 65px">
      <div class="left-box">
        <div class="title">
          照护计划模板列表
          <el-button
            type="primary"
            size="default"
            style="position: relative; top: 13px; float: right"
            plain
            icon="Refresh"
            @click="LoadCarePlanTemplateList"
          >
            刷新照护计划模板列表
          </el-button>
        </div>
        <div class="left-table">
          <el-table :data="tableData" style="width: 100%" height="100%" border>
            <el-table-column label="模板来源" width="97" align="center">
              <template #default="scope">
                <span v-if="scope.row.companyId == 1">
                  <el-tag type="success" effect="dark" size="small">平台推荐</el-tag>
                </span>
                <span v-else>
                  <el-tag type="primary" effect="dark" size="small">自建模板</el-tag>
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="模板名称" />
            <el-table-column fixed="right" label="操作" width="80" align="center">
              <template #default="scope">
                <el-button link type="primary" size="small" icon="Select" @click="SelectCarePlanTemplate(scope.row)">
                  选择
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="right-box">
        <div class="title">照护计划模板详情</div>
        <div class="detail-box">
          <div class="detail-item">
            <div class="item-nme">当前选择模板</div>
            <div class="item-context">
              <span style="font-size: 18px; font-weight: 500">{{ detailData.name }}</span>
            </div>
          </div>
          <div class="detail-item">
            <div class="item-nme" style="position: relative">照护项目</div>
            <div class="item-context">
              <div>
                <el-table :span-method="objectSpanMethod" :data="detailCareMissionList" border>
                  <el-table-column prop="name" label="建议实施时段" width="170" align="center" fixed="left">
                    <template #default="scope">
                      <div v-if="scope.row.isDailyMission">
                        每日：
                        <span v-if="scope.row.dailyMissionStartTime && scope.row.dailyMissionEndTime">
                          {{ scope.row.dailyMissionStartTime }} - {{ scope.row.dailyMissionEndTime }}
                        </span>
                        <span v-else> 不限制时间段 </span>
                      </div>

                      <span v-else> 根据需求及老人情况 </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="name" label="项目名称" width="350" />
                  <el-table-column prop="dailyMissionExecutionCount" label="建议执行次数" width="130" align="center">
                    <template #default="scope">
                      <span v-if="scope.row.dailyMissionExecutionCount">{{ scope.row.dailyMissionExecutionCount }} 次</span>
                      <span v-else> -- </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="description" label="注意事项" min-width="500" />
                </el-table>
              </div>
            </div>
          </div>
          <div class="detail-item" style="top: revert; bottom: 153px; height: 180px">
            <div class="item-nme">个性化照护需求</div>
            <div class="item-context">
              <el-input
                :disabled="true"
                v-model="detailData.personalizedCareNeeds"
                :rows="5"
                type="textarea"
                style="width: 100%"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <el-button @click="drawerProps.drawerVisible = false" icon="Close">取消</el-button>
      <el-button type="primary" @click="useCurrentTemplate" icon="Select">使用当前选择模板</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, defineEmits } from "vue";
import { getCarePlanTemplateList, getCarePlanTemplateDetail } from "@/api/modules/care-plan-template";
import type { CarePlanTemplate } from "@/api/interface";
import { TableColumnCtx } from "element-plus";

// 照护计划模板列表
const tableData = ref<CarePlanTemplate.ResCarePlanTemplate[]>([]);
const detailCareMissionList = ref<CarePlanTemplate.ResCarePlanTemplateMissionDto[]>([]);
const detailData = ref<CarePlanTemplate.ResCarePlanTemplate>({ id: 0, companyId: 0, name: "", sort: 0, missionList: [] });

// 组件挂载时加载照护计划模板列表
onMounted(async () => {
  await LoadCarePlanTemplateList();
});

// 抽屉组件参数接口
interface DrawerProps {
  drawerVisible: boolean;
  title: string;
}

// 抽屉组件参数
const drawerProps = ref<DrawerProps>({
  drawerVisible: false,
  title: "选择照护项目"
});

// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
};

// 暴露方法给父组件调用
defineExpose({
  // 接收父组件传过来的参数
  acceptParams
});

// 加载照护计划模板列表
const LoadCarePlanTemplateList = async () => {
  const res = await getCarePlanTemplateList();
  tableData.value = res.data || [];
  if (tableData.value.length > 0) {
    detailData.value = tableData.value[0];
    await getDetail(tableData.value[0].id);
  }
};

// 获取照护计划模板详情
const getDetail = async (id: number) => {
  const res = await getCarePlanTemplateDetail(id);
  detailCareMissionList.value = JSON.parse(JSON.stringify(res.data.missionList || "[]"));
  detailData.value.missionList = detailCareMissionList.value;
};

// 表格合并行方法
interface SpanMethodProps {
  row: CarePlanTemplate.ResCarePlanTemplateMissionDto;
  column: TableColumnCtx<CarePlanTemplate.ResCarePlanTemplateMissionDto>;
  rowIndex: number;
  columnIndex: number;
}
// 合并行方法
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {
  console.log(column);
  if (columnIndex === 0) {
    // 只合并第一列
    // 计算相同时间段的连续行数
    let rowspan = 1;
    for (let i = rowIndex + 1; i < detailCareMissionList.value.length; i++) {
      const current = detailCareMissionList.value[i];
      const prev = detailCareMissionList.value[i - 1];

      if (
        current.dailyMissionStartTimeValue === prev.dailyMissionStartTimeValue &&
        current.dailyMissionEndTimeValue === prev.dailyMissionEndTimeValue &&
        current.isDailyMission === prev.isDailyMission
      ) {
        rowspan++;
      } else {
        break;
      }
    }

    // 如果是合并区域的第一行，返回合并的行数
    if (
      rowIndex === 0 ||
      row.dailyMissionStartTimeValue !== detailCareMissionList.value[rowIndex - 1].dailyMissionStartTimeValue ||
      row.dailyMissionEndTimeValue !== detailCareMissionList.value[rowIndex - 1].dailyMissionEndTimeValue ||
      row.isDailyMission !== detailCareMissionList.value[rowIndex - 1].isDailyMission
    ) {
      return {
        rowspan: rowspan,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
};
// 选择照护计划模板
const SelectCarePlanTemplate = async (row: CarePlanTemplate.ResCarePlanTemplate) => {
  detailData.value = row;
  await getDetail(row.id);
};
// 回调事件：使用当前选择模板
const emit = defineEmits<{
  (event: "change", payload: CarePlanTemplate.ResCarePlanTemplate): void;
}>();
// 使用当前选择模板
const useCurrentTemplate = () => {
  emit("change", detailData.value);
  drawerProps.value.drawerVisible = false;
};
</script>
<style scoped lang="scss">
.content-box {
  position: relative;
}
.left-box {
  position: absolute;
  top: 0;
  left: 0;
  width: 500px;
  height: 100%;
  border-right: 1px solid var(--el-aside-border-color);
}
.left-box .title {
  position: absolute;
  top: 0;
  right: 8px;
  left: 15px;
  height: 55px;
  line-height: 55px;
}
.left-box .left-table {
  position: absolute;
  top: 55px;
  bottom: 0;
  left: 0;
  width: 500px;
}
.right-box {
  position: absolute;
  inset: 0 0 0 500px;
}
.right-box .title {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  width: 100%;
  height: 55px;
  padding-left: 17px;
  line-height: 55px;
  border-bottom: 1px solid var(--el-aside-border-color);
}
.right-box .detail-box {
  position: absolute;
  inset: 55px 0 10px 10px;
  overflow: auto;
}
.right-box .detail-box .detail-item {
  margin-top: 10px;
  border: 1px solid var(--el-aside-border-color);
}
.right-box .detail-box .detail-item .item-nme {
  height: 50px;
  padding-left: 10px;
  line-height: 48px;
  background-color: var(--el-color-primary-light-9);
}
.right-box .detail-box .detail-item .item-context {
  padding: 10px;
}
</style>
